/**
 * 
 */
package hr.fer.zemris.revhttp.gateway.websockets;

import hr.fer.zemris.revhttp.gateway.resources.GatewayResources;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.continuation.Continuation;
import org.eclipse.jetty.continuation.ContinuationSupport;

/**
 * @author tomek
 */
public class ProxyServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public static Map<String, HttpServletRequest> requestMap = new HashMap<String, HttpServletRequest>();
	public static Map<String, HttpServletResponse> responseMap = new HashMap<String, HttpServletResponse>();

	public String reqId;
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		final Continuation continuation = ContinuationSupport.getContinuation(request);
		
		if (continuation.isResumed()) {
			if (continuation.isExpired()) {
				System.out.println("Timeout aplikacije prijavljene na " + request.getPathInfo());
				response.setStatus(504);
				return;
			}
			System.out.println("Dobil sam odgovor s aplikacije prijavljene na " + request.getPathInfo());
			response.setContentType("text/html;charset=utf-8");
			response.getWriter().print(responseMap.get(reqId));
			requestMap.remove(reqId);
			responseMap.remove(reqId);
			return;
		}
		
		System.out.println("Primil sam zahtjev na " + request.getPathInfo());
		

		reqId = GatewayResources.generateUUID();
		if (GatewayResources.relay(reqId, request.getPathInfo())) {
			System.out.println("Poslal sam zahtjev s " + request.getPathInfo() + " na obradu");
			requestMap.put(reqId, request);
			responseMap.put(reqId, response);
			continuation.suspend();
		} else {
			response.getWriter()
					.print("No registered application found!");
		}
	}
}
